package javafoundation.notes;

import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName Https请求
 * @Description Https请求企业微信查询
 * @Author dzf
 * @Date 2022/11/11 15:11
 * @Version 1.0
 */
public class Https请求企业微信 {

    //企业调用接口凭证
    public static String ACCESS_TOKEN;
    //企业ID
//    public static String ID = "wwb37ebdf668015f5e";//志锋开发
    public static String ID = "ww50b61fa31448f2c0";
    //应用的凭证密钥
//    public static String SECRET = "gg-lBlV8Z5TG3v0Mxt46lx33fRmW90wu7HXw-vWMxYU";//志锋开发-审批应用
    public static String SECRET = "zaykgHIifkemKflocd1QPtE-IufSGwKANkxPk4jR_nE";

    //应用id
    public static String AGENTID = "1000003";
    //OAuth2.0链接返回的CODE
    public static String CODE = "r-q9NxV4dlfDxFJ7rcZHyXssSPa3VLcXVvIeFrfOVl0&state";

    public static void main(String[] args) throws IOException {
        //redis中获取ACCESS_TOKEN


        //获取userid
        String userid = "";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" + ACCESS_TOKEN + "&code=" + CODE;
        String request = "GET";
        JSONObject jo = getJsonObject(url, request);
        String s = jo.get("errcode").toString();

        if (!"0".equals(s)) {
            //token失效，重新获取
            getToken();
            url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" + ACCESS_TOKEN + "&code=" + CODE;
            System.out.println(url);
            jo = getJsonObject(url, request);
            s = jo.get("errcode").toString();
            if ("0".equals(s)){
                userid = jo.get("userid").toString();
                boolean boo = getUserInfo(userid);
                System.out.println(boo);
            } else if ("40029".equals(s)){
                System.out.println("不合法的CODE");
            }
        } else {
            if ("0".equals(s)){
                userid = jo.get("userid").toString();
                boolean boo = getUserInfo(userid);
                System.out.println(boo);
            } else if ("40029".equals(s)){
                System.out.println("不合法的CODE");
            }
        }
    }

    private static void getToken() throws IOException {
        //企业微信获取ACCESS_TOKEN接口
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret=" + SECRET;
        String request = "GET";
        JSONObject jo = getJsonObject(url, request);
        String errcode = jo.get("errcode").toString();
        if (!"0".equals(errcode)) {
            System.out.println("token获取失败,失败码：" + errcode);
        }else {
            ACCESS_TOKEN = jo.get("access_token").toString();
        }
    }

    /**
     * 获取JSON字符串对象
     *
     * @param url
     * @param request
     * @return com.google.gson.JsonObject
     * @author 杜志锋
     * @date 2021/4/28 11:02
     */
    private static JSONObject getJsonObject(String url, String request) throws IOException {
        URL reqURL = new URL(url); //创建URL对象
        HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL.openConnection();

        httpsConn.setDoOutput(true);
        httpsConn.setRequestMethod(request);
        OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream());
//        out.write("xxxx");
        out.flush();
        out.close();
        //取得该连接的输入流，以读取响应内容 
        InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());
        //读取服务器的响应内容并显示
        int respInt = insr.read();
        StringBuffer buffer = new StringBuffer();
        while (respInt != -1) {
            buffer = buffer.append((char) respInt);
            respInt = insr.read();
        }
        String str = new String(buffer);
        System.out.println("链接返回的JSON字符串 " + str);
        return JSONObject.parseObject(str);
    }

    /**
     *
     * @Description 获取用户详情
     * @author dzf
     * @date 2022/11/17 15:19
     * @params [userid]
     * @return boolean
     * @Version1.0
     **/
    private static boolean getUserInfo(String userid) throws IOException {
        boolean boo = false;
        //获取指定的应用详情
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + ACCESS_TOKEN + "&userid=" + userid;
        String request = "GET";
        JSONObject jo = getJsonObject(url, request);
        String errcode = jo.get("errcode").toString();
        if ("0".equals(errcode)) {
            boo = true;
        } else {
            System.out.println("获取用户详情失败，失败码：" + errcode);
        }
        return boo;
    }

    private static List<Map> getUserList() throws IOException {
        List<Map> userList = new ArrayList<>();
        //获取指定的应用详情
        String url = "https://qyapi.weixin.qq.com/cgi-bin/agent/get?access_token=" + ACCESS_TOKEN + "&agentid=" + AGENTID;
        String request = "POST";

        JSONObject jo = getJsonObject(url, request);
        Map userInfos = (Map) jo.get("allow_userinfos");//企业应用可见范围（人员）
        Map partys = (Map) jo.get("allow_partys");//企业应用可见范围（部门）
        Map tags = (Map) jo.get("allow_tags");//企业应用可见范围（标签）
        String close = (String) jo.get("close");//企业应用是否被停用
        if ("0".equals(close)) {
            userList = (List<Map>) userInfos.get("user");
            for (Map map : userList) {
                String userid = (String) map.get("userid");
                System.out.println(userid);
            }

            List<Integer> partyid = (List<Integer>) partys.get("partyid");
            if (partyid.size()>0){
                for (Integer integer : partyid) {

                }
            }
        }

        return  userList;
    }

}
